package com.rxyb.security.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rxyb.security.db.bean.SysRole;
import com.rxyb.security.db.bean.SysUser;
import com.rxyb.security.db.bean.SysUserRole;
import com.rxyb.security.db.bean.SysUsercustom;
import com.rxyb.security.db.dao.SysRoleMapper;
import com.rxyb.security.db.dao.SysUserMapper;
import com.rxyb.security.db.dao.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YJH
 * @version 1.0
 * @description 验证
 * @date 2020/5/20  14:19
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    private final SysUserMapper sysUserMapper;

    private final SysRoleMapper sysRoleMapper;

    private final SysUserRoleMapper sysUserRoleMapper;

    public SecurityConfiguration(SysUserMapper sysUserMapper, SysRoleMapper sysRoleMapper, SysUserRoleMapper sysUserRoleMapper) {
        this.sysUserMapper = sysUserMapper;
        this.sysRoleMapper = sysRoleMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        String pwd = new BCryptPasswordEncoder().encode("123456");//对密码进行加密
//        manager.createUser(User.withUsername("user_1").password(pwd).authorities("USER").build());
//        manager.createUser(User.withUsername("user_2").password(pwd).authorities("USER").build());
//        return manager;
        return username -> {
            if (null == username || username.trim().length() <= 0) {
                throw new UsernameNotFoundException("用户名为空");
            }
//            // 查询用户信息
            QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
            sysUserQueryWrapper.lambda().eq(SysUser::getUsername, username);
            SysUser sysUser1 = sysUserMapper.selectOne(sysUserQueryWrapper);
            // 查询权限信息
            QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
            sysUserRoleQueryWrapper.lambda().eq(SysUserRole::getSysUserId, sysUser1.getId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleQueryWrapper);
            //  查询权限
            QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
            sysRoleQueryWrapper.lambda().in(SysRole::getId, str(sysUserRoles));
            List<SysRole> sysRoles = sysRoleMapper.selectList(sysRoleQueryWrapper);
            SysUsercustom sysUser = new SysUsercustom();
            sysUser.setId(sysUser1.getId());
            sysUser.setUsername(sysUser1.getUsername());
            sysUser.setPassword(sysUser1.getPassword());
            sysUser.setSysRoleList(sysRoles);
            if (null != sysUser) {
                return sysUser;
            }
            throw new UsernameNotFoundException("用户信息不存在");
        };
    }
    private List<Long> str(List<SysUserRole> roles) {
        List<Long> list = new ArrayList<>();
        roles.forEach(e -> {
            list.add(e.getSysRoleId());
        });
        return list;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/*").permitAll();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
